package selenium;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

public class test1 {

	@SuppressWarnings("resource")
	public static void main(String[] args) {
		String filepath = "G:\\1";// 视频文件夹路径
		String zhangHaofilepath = "E:\\ZhangHao";// 帐号文件夹路径
		String filepath1 = filepath.replace("\\", "\\\\");
		File fileExist = new File(filepath + "/a.txt");
		if (!fileExist.exists()) {
			File file = new File(filepath);
			if (!file.isDirectory()) {
				System.out.println("这是个文件");
				System.out.println("path=" + file.getPath());
				System.out.println("absolutepath=" + file.getAbsolutePath());
				System.out.println("name=" + file.getName());

			} else if (file.isDirectory()) {
				System.out.println("这是个文件夹");
				System.out.println("path=" + file.getPath());
				System.out.println("absolutepath=" + file.getAbsolutePath());
				System.out.println("name=" + file.getName());
				String[] filelist = file.list();
				for (int i = 0; i < filelist.length; i++) {
					method2(filepath + "/a" + ".txt", filepath1 + "/" + filelist[i]);
				}
			}
		}
        
        
	
		final WebDriver driver = new ChromeDriver();
		try {
			driver.manage().window().maximize();
			driver.get("http://mp.163.com/index.html");
			driver.navigate().refresh();
			for (int z = 0; z < 999; z++) {
			driver.manage().deleteAllCookies();
			SimpleDateFormat sdf = new SimpleDateFormat("M/dd/yyyy hh:mm:ss a",Locale.US);
			
			String name = "NTES_SESS";
			// 读取帐号文件
			File filename2 = new File(zhangHaofilepath + "/a.txt"); // 读帐号文件
			InputStreamReader reader2 = new InputStreamReader(new FileInputStream(filename2)); // 建立一个输入流对象reader
			BufferedReader br2 = new BufferedReader(reader2); // 建立一个对象，它把文件内容转成计算机能读懂的语言
			String line2 = "";
			line2 = br2.readLine().trim();
			String[] s1 = line2.split("\\/", -1);
			String value = s1[3];
			System.out.println("---------------start---------------------");
			System.out.println(s1[0]+"。开始执行上传任务");
			System.out.println("读入帐号成功：" + value);
			
			String domain = ".mp.163.com";
			String path = "/";
			Date expiry = sdf.parse("5/13/2103 10:31:37 AM");
			Cookie cookie = new Cookie(name, value, domain, path, expiry);

			driver.manage().addCookie(cookie);
			Thread.sleep(400);
			driver.get("http://mp.163.com/index.html#/income-stat");
			driver.navigate().refresh();
			System.out.println("正在读入网易指数");
			(new WebDriverWait(driver, 9)).until(new ExpectedCondition<WebElement>() {
				@Override
				public WebElement apply(WebDriver arg0) {
					WebElement sDriver = driver.findElement(By.className("slide-entered"));
					if (sDriver != null) {
						return sDriver;
					} else {
						return null;
					}
				}
			});

			WebElement ddElement1 = driver.findElement(By.xpath("//*[@class='column column-5']/div/ul/li[2]/a"));
			String idString = ddElement1.getAttribute("href").toString().replace("http://mp.163.com/article/postpage/",
					"");
			String videoUrl = "http://mp.163.com/video/postpage/" + idString +"?";
			for (int i = 0; i < 6; i++) {
				if (i > 5) {
					continue;
				}
				driver.get(videoUrl);
				driver.navigate().refresh();
				// 读取视频地址
				File filename1 = new File(filepath + "/a.txt"); // 要读取以上路径的input。txt文件
				InputStreamReader reader = new InputStreamReader(new FileInputStream(filename1)); // 建立一个输入流对象reader
				BufferedReader br = new BufferedReader(reader); // 建立一个对象，它把文件内容转成计算机能读懂的语言
				String line1 = "";
				line1 = br.readLine().trim();
				System.out.println("读入视频文件成功：" + line1);
				Thread.sleep(100);
				driver.findElement(By.id("video-up-input")).sendKeys(line1);
				// 删除第一行
				List<String> list = readFile(filepath + "/a.txt", line1);
				writeFile(filepath + "/a.txt", list);
				Thread.sleep(200);
				// z-red-font读出次数
				WebElement iDriver = driver.findElement(By.className("z-red-font"));
				String iString = iDriver.getText().toString();
				i = Integer.parseInt(iString);
				System.out.println("正在处理第" + (i + 1) +"个视频");
				if(i>5){
					driver.get("http://mp.163.com/index.html#/income-stat");
					continue;
				}
				driver.findElement(By.xpath("//form[@id='videoPost']/div[2]/div[6]/div/ul/li[1]/a/label")).click();
				////////////////////////////////////////////////////////////////////
				// *[@id='videoPost']/div[2]/div[4]/div/div[1]/button
				
				//driver.findElement(By.linkText("电视剧")).click();
				//*[@id="videoPost"]/div[2]/div[4]/div/div[1]/div/div/input
				/*(new WebDriverWait(driver, 50)).until(new ExpectedCondition<WebElement>() {
					@Override
					public WebElement apply(WebDriver arg0) {
						//*[@id="videoPost"]/div[2]/div[4]/div/div[1]/div/ul/li[46]/a/span[1]
						WebElement suuDriver = driver.findElement(By.linkText("电视剧"));
						if (suuDriver != null) {
							return suuDriver;
						} else {
							return null;
						}
					}
				});*/
				Actions action = new Actions(driver);
				driver.findElement(By.xpath("//*[@id='videoPost']/div[2]/div[4]/div/div[1]/button")).click();
				Thread.sleep(100);
				driver.findElement(By.xpath("//*[@id='videoPost']/div[2]/div[4]/div/div[1]/div/div/input")).sendKeys("电视剧");
				driver.findElement(By.xpath("//*[@id='videoPost']/div[2]/div[4]/div/div[1]/div/div/input")).clear();
				driver.findElement(By.xpath("//*[@id='videoPost']/div[2]/div[4]/div/div[1]/div/div/input")).sendKeys("电视剧");
				//*[@id="videoPost"]/div[2]/div[4]/div/div[1]/div/ul/li[46]/a/span[1]
				(new WebDriverWait(driver, 9)).until(new ExpectedCondition<WebElement>() {
					@Override
					public WebElement apply(WebDriver arg0) {
						//*[@id="videoPost"]/div[2]/div[4]/div/div[1]/div/ul/li[46]/a/span[1]
						WebElement suuDriver = driver
								.findElement(By.xpath("//*[@id='videoPost']/div[2]/div[4]/div/div[1]/div/ul/li[46]/a/span[1]"));
							if (suuDriver != null && "电视剧".equals(suuDriver.getText().toString())) {
							return suuDriver;
						} else {
							return null;
						}
					}
				});
				action.sendKeys(Keys.ENTER).perform();
				//driver.findElement(By.linkText("电视剧")).click();
				
				driver.findElement(By.id("form-tags-input")).sendKeys("电影");
				action.sendKeys(Keys.SPACE).perform();
				driver.findElement(By.id("form-tags-input")).sendKeys("电视剧");
				action.sendKeys(Keys.SPACE).perform();
				driver.findElement(By.id("form-tags-input")).sendKeys("综艺");
				action.sendKeys(Keys.SPACE).perform();
				driver.findElement(By.id("form-tags-input")).sendKeys("娱乐");
				action.sendKeys(Keys.SPACE).perform();
				driver.findElement(By.id("form-tags-input")).sendKeys("明星");
				action.sendKeys(Keys.SPACE).perform();

				/*File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
				try {
					FileUtils.copyFile(srcFile, new File("d:\\hehe\\" + i + idString + ".png"));
				} catch (IOException e) {
					e.printStackTrace();
				}*/

				// *[@id='videoPost']/div[2]/div[4]/div/div[2]/button
				// filter-option pull-left
				driver.findElement(By.xpath("//*[@id='videoPost']/div[2]/div[4]/div/div[2]/button")).click();
				(new WebDriverWait(driver, 9)).until(new ExpectedCondition<WebElement>() {
					@Override
					public WebElement apply(WebDriver arg0) {
						//*[@id="videoPost"]/div[2]/div[4]/div/div[1]/div/ul/li[46]/a/span[1]
						WebElement suuDriver = driver.findElement(By.linkText("电视剧片段"));
						if (suuDriver != null) {
							return suuDriver;
						} else {
							return null;
						}
					}
				});
				driver.findElement(By.linkText("电视剧片段")).click();
				String valueFileTitle = driver.findElement(By.id("fileTitle")).getAttribute("value")
						.trim().replaceAll(" ", "").replace("…", "");
				System.out.println("start标题长度为："+valueFileTitle.length());
				System.out.println("start标题为："+valueFileTitle);
				String valueFileTitleNew = valueFileTitle;
				String valueFileTitle1 = valueFileTitle;
				if (valueFileTitle.length() > 27) {
					int gg = 0;
					int length1 = valueFileTitle.split("\\,").length;
					int length2 = valueFileTitle.split("\\.").length;
					int length3 = valueFileTitle.split("\\?").length;
					int length4 = valueFileTitle.split("\\？").length;
					int length5 = valueFileTitle.split("\\。").length;
					int length6 = valueFileTitle.split("\\，").length;
					int length7 = valueFileTitle.split("\"").length;
					int length8 = valueFileTitle.split("\'").length;
					int length9 = valueFileTitle.split("\\《").length;
					int length10 = valueFileTitle.split("\\》").length;
					int length11 = valueFileTitle.split("\\<").length;
					int length12 = valueFileTitle.split("\\>").length;
					int length13 = valueFileTitle.split("\\(").length;
					int length14 = valueFileTitle.split("\\)").length;
					int length15 = valueFileTitle.split("\\:").length;
					int length16 = valueFileTitle.split("#").length;
					if(length1>1){
						gg=gg+(length1+1)/2;
					};
					if(length2>1){
						gg=gg+(length2+1)/2;
					};
					if(length3>1){
						gg=gg+(length3+1)/2;
					};
					if(length4>1){
						gg=gg+(length4+1)/2;
					};
					if(length5>1){
						gg=gg+(length5+1)/2;
					};
					if(length6>1){
						gg=gg+(length6+1)/2;
					};
					if(length7>1){
						gg=gg+(length7+1)/2;
					};
					if(length8>1){
						gg=gg+(length8+1)/2;
					};
					if(length9>1){
						gg=gg+(length9+1)/2;
					};
					if(length10>1){
						gg=gg+(length10+1)/2;
					};
					if(length11>1){
						gg=gg+(length11+1)/2;
					};
					if(length12>1){
						gg=gg+(length12+1)/2;
					};
					if(length13>1){
						gg=gg+(length13+1)/2;
					};
					if(length14>1){
						gg=gg+(length14+1)/2;
					};
					if(length15>1){
						gg=gg+(length15+1)/2;
					};
					if(length16>1){
						gg=gg+(length16+1)/2;
					};
					if(1==gg){
						gg=0;
					};
					if(gg>1){
						gg=(gg+1)/2;
					};
					
					System.out.println("GG="+gg);
					int length = valueFileTitleNew.length();
					if(length-gg+1<=27){
						valueFileTitle1 = valueFileTitleNew;
					}else {
						valueFileTitle1 = valueFileTitleNew.substring(0, 27+gg);//网易算法有问题所以是28
					}
					System.out.println("end标题长度为："+valueFileTitle1.length());
					System.out.println("end标题为："+valueFileTitle1);
				}
				if(valueFileTitle.length()<12){
					valueFileTitle1= valueFileTitle1+"。"+valueFileTitle;
					if(valueFileTitle1.length()<12){
						valueFileTitle1= valueFileTitle1+"。"+valueFileTitle1;
					}
				}
				driver.findElement(By.id("fileTitle")).clear();
				driver.findElement(By.id("fileTitle")).sendKeys(valueFileTitle1);
				driver.findElement(By.id("description")).sendKeys(valueFileTitleNew + "/" + valueFileTitleNew);

				WebDriverWait wait = new WebDriverWait(driver, 30);
				wait.until(new ExpectedCondition<WebElement>() {
					@Override
					public WebElement apply(WebDriver d) {
						WebElement ddElement = driver.findElement(By.className("radio-img"));
						System.out.println("等待上传到100%");
						if (ddElement != null) {
							return ddElement;
						} else {
							return null;
						}
					}
				});
				// .//*[@id='auto']/ul/li[5]/input

				driver.findElement(By.xpath("//*[@id='auto']/ul/li[5]")).click();
				System.out.println("第5张图片成功选中");
				// .//*[@id='videoPost']/div[2]/div[7]/button
				
				//dy-icon-remove
				WebElement sDriver22 = driver.findElement(By.xpath("//*[@id='videoPost']/div[2]/div[1]/div/p[1]"));
				String aaa = sDriver22.getAttribute("style").toString();//display: block;
				if("display: block;".equals(aaa)){
					String valueFileTitle2 = valueFileTitleNew.substring(0, 27);//网易算法有问题所以是28
					driver.findElement(By.id("fileTitle")).clear();
					driver.findElement(By.id("fileTitle")).sendKeys(valueFileTitle2);
				};
				driver.findElement(By.xpath("//*[@id='videoPost']/div[2]/div[7]/button")).click();
				System.out.println("提交按钮成功点击");
				(new WebDriverWait(driver, 9)).until(new ExpectedCondition<WebElement>() {
					@Override
					public WebElement apply(WebDriver arg0) {
						WebElement sDriver = driver.findElement(By.className("js-btn-ok"));
						if (sDriver != null&&"确定".equals(sDriver.getText().toString())) {
							return sDriver;
						} else {
							return null;
						}
					}
				});
				driver.findElement(By.className("js-btn-ok")).click();
				System.out.println("等待跳过弹窗");
				(new WebDriverWait(driver, 9)).until(new ExpectedCondition<WebElement>() {
					@Override
					public WebElement apply(WebDriver arg0) {
						WebElement sDriver = driver.findElement(By.className("panel-heading"));
						if (sDriver != null&&"内容管理".equals(sDriver.getText().toString())) {
							return sDriver;
						} else {
							return null;
						}
					}
				});
				if (i >= 5) {
					//driver.get("http://mp.163.com/index.html");
					driver.manage().deleteAllCookies();
					System.out.println("本账号发送完毕，正在准备发送另外一个账号");
				}
			}
			// 删除第一行
			List<String> list = readFile(zhangHaofilepath + "/a.txt", line2);
			writeFile(zhangHaofilepath + "/a.txt", list);
			
			System.out.println(s1[0]+"6个视频成功上传完毕");
			System.out.println("---------------end---------------------");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		 driver.quit();
	};




	// 方法1：

	public void method1() {
		FileWriter fw = null;
		try {
			// 如果文件存在，则追加内容；如果文件不存在，则创建文件
			File f = new File("E:\\dd.txt");
			fw = new FileWriter(f, true);
		} catch (IOException e) {
			e.printStackTrace();
		}
		PrintWriter pw = new PrintWriter(fw);
		pw.println("追加内容");
		pw.flush();
		try {
			fw.flush();
			pw.close();
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 方法2：

	public static void method2(String file, String conent) {
		BufferedWriter out = null;
		try {
			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
			out.write(conent + "\r\n");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	// 方法3：

	public static void method3(String fileName, String content) {
		try {
			// 打开一个随机访问文件流，按读写方式
			RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
			// 文件长度，字节数
			long fileLength = randomFile.length();
			// 将写文件指针移到文件尾。
			randomFile.seek(fileLength);
			randomFile.writeBytes(content + "\r\n");
			randomFile.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static List<String> readFile(String filePath, String str) throws IOException {
		File file = new File(filePath);
		BufferedReader reader = null;
		List<String> list = new ArrayList<String>();
		reader = new BufferedReader(new FileReader(file));
		String text = reader.readLine();
		while (text != null) {
			if (!text.trim().equals(str)) {
				list.add(text + "\r\n");
			}
			text = reader.readLine();
		}
		reader.close();
		return list;
	}

	public static void writeFile(String filePath, List<String> list) throws IOException {
		File file = new File(filePath);
		if (!file.exists()) {
			file.createNewFile();
		}
		FileOutputStream outputStream = new FileOutputStream(file);
		for (String s : list) {
			outputStream.write(s.getBytes());
		}
		outputStream.close();
	}

}
